#!/usr/bin/env python3
"""
测试带延迟的视频拆分
"""

import asyncio
from pathlib import Path
from app.services.video_splitter import VideoSplitter
import shutil

async def test_with_delay():
    """测试带延迟的视频拆分"""
    
    video_path = Path("uploads/ed0df223-f7c5-4a97-9ace-f3bed83ca3a3.mp4")
    
    if not video_path.exists():
        print(f"❌ 视频文件不存在: {video_path}")
        return
    
    print(f"🧪 测试带延迟的视频拆分")
    print(f"📹 视频文件: {video_path}")
    
    # 清理之前的片段
    video_id = video_path.stem
    segment_dir = Path("uploads/segments") / video_id
    if segment_dir.exists():
        shutil.rmtree(segment_dir)
        print(f"🧹 已清理旧片段目录")
    
    splitter = VideoSplitter()
    
    try:
        # 测试拆分（限制为5个片段进行快速测试）
        print(f"\n🔄 开始拆分测试（5个片段）...")
        
        result = await splitter.split_video_by_duration(
            video_path, 
            segment_duration=60,
            max_segments=5,  # 先测试5个片段
            min_segment_duration=10
        )
        
        segments_count = len(result.get('segments', []))
        print(f"   拆分结果: {segments_count} 个片段")
        
        if segments_count > 0:
            print(f"   ✅ 拆分成功！")
            
            # 检查文件
            total_size = 0
            for i, segment in enumerate(result['segments']):
                segment_path = Path(segment['path'])
                if segment_path.exists():
                    size = segment_path.stat().st_size
                    total_size += size
                    print(f"     片段{i+1}: {segment['filename']} ({size} bytes)")
                else:
                    print(f"     ❌ 片段{i+1}: {segment['filename']} 文件不存在")
            
            print(f"   总大小: {total_size} bytes")
            
            if total_size > 1000:  # 如果总大小合理
                print(f"\n🎯 5个片段测试成功，尝试完整拆分...")
                
                # 清理测试片段
                if segment_dir.exists():
                    shutil.rmtree(segment_dir)
                
                # 完整拆分
                result_full = await splitter.split_video_by_duration(
                    video_path, 
                    segment_duration=60,
                    max_segments=50,
                    min_segment_duration=10
                )
                
                full_segments_count = len(result_full.get('segments', []))
                print(f"   完整拆分结果: {full_segments_count} 个片段")
                
                if full_segments_count > 0:
                    print(f"   ✅ 完整拆分成功！")
                else:
                    print(f"   ❌ 完整拆分失败")
            else:
                print(f"   ⚠️ 片段文件太小，可能有问题")
        else:
            print(f"   ❌ 拆分失败")
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(test_with_delay())